﻿using DevExpress.Mvvm;
using PlaceOrder_Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace PlaceOrder_Client.Views
{
    /// <summary>
    /// PingCangView.xaml 的交互逻辑
    /// </summary>
    public partial class PingCangView : Window
    {
        // 静态字段保存唯一的实例
        private static PingCangView _instance;
        private PingCangViewModel _viewModel;
        public PingCangView()
        {
            InitializeComponent();
            Messenger.Default.Register<string>(this, CloseWindow);
        }

        // 公共方法获取唯一实例
        public static PingCangView GetInstance(PingCangViewModel viewModel, Window parentWindow)
        {
            if (_instance == null || !_instance.IsLoaded)
            {
                _instance = new PingCangView
                {
                    DataContext = viewModel,
                    Owner = parentWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner
                };
                _instance._viewModel = viewModel;
            }
            return _instance;
        }

        private void CloseWindow(string obj)
        {
            this.Close();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        // 重写 OnClosed 方法来处理视图模型的置空
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            // 置空视图模型
            _viewModel = null;

            // 将实例字段置为空，以便下次创建新实例
            _instance = null;
        }

        private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            string keyValue = e.Key.ToString();
            switch (keyValue)
            {
                case "Up":
                    this.orderPrice.Value += 0.0005;
                    break;
                case "Down":
                    this.orderPrice.Value = this.orderPrice.Value <= 0 ? 0 : this.orderPrice.Value - 0.0005;
                    break;
                case "Left":
                    this.orderPrice.Value = this.orderPrice.Value <= 0 ? 0 : this.orderPrice.Value - 0.0025;
                    break;
                case "Right":
                    this.orderPrice.Value += 0.0025;
                    break;
            }
        }
    }
}
